//
//  SubBViewController.swift
//  xiaoqiao
//
//  Created by 冷子豪 on 2017/8/19.
//  Copyright © 2017年 冷子豪. All rights reserved.
//

import UIKit

class SubBViewController: UITableViewController {
    
    var subUserList = [User]()
    var userid:Int?
    
    /// 完成回调属性
    var completionCallBack:(()->())?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
        tableView.dataSource = self
        
        loadData { (list) in
            // ‘拼接’数组,闭包中定义好的代码在需要的时候执行，需要self，指定语境
            self.subUserList += list
            
            // 刷新表格
            self.tableView.reloadData()
        }
    }
    
    /// 利用闭包回调
    private func loadData(completion:@escaping ([User]) -> ()) -> () {
        
        DispatchQueue.global().async {
            print("加载B级下线信息中……")
            
            Thread.sleep(forTimeInterval: 0.1)
            
            // 同步Get方式
            
            let arrayM = inviteViewModel.getDownGradeByUserId(userid: self.userid!)
            
            // 主线程回调
            DispatchQueue.main.async(execute: {
                
                // 回调，执行闭包
                completion(arrayM)
            })
        }
    }
    
    //MARK: - 控制器跳转方法
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "subB2C"{
            // 类型转换
            let vc = segue.destination as! SubCViewController
            
            // 设置选中的 id，indexPath
            if let indexPath = sender as? IndexPath {
                // indexPath 一定有值
                vc.userid = subUserList[indexPath.row].id
                
                // 设置编辑完成的闭包
                vc.completionCallBack = {
                    // 刷新制定行
                    self.tableView.reloadRows(at: [indexPath], with: .automatic)
                }
            } else {
                //                vc.completionCallBack = {
                //
                //                    // 1. 获取明细控制器的 house
                //                    guard let h = vc.house,h.numOfCertificate != "" else{
                //                        return
                //                    }
                //                    // 2. 插入到数组顶部
                //                    self.houseList.insert(h, at: 0)
                //
                //                    // 3. 刷新表格
                //                    self.houseTable.reloadData()
                //                }
            }
        } else {
            print("*****  未知错误1  *****")
        }
        
    }
    
    // MARK: - 代理方法
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        //        houseTable.deselectRow(at: indexPath, animated: true)
        
        // 执行 segue
        performSegue(withIdentifier: "subB2C", sender: indexPath)
    }
    
    // MARK: - 数据源方法
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return subUserList.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "subid", for: indexPath)
        
        // 1
        let gradeLabel:UILabel = cell.viewWithTag(1) as! UILabel
        gradeLabel.text = "\(String(describing: subUserList[indexPath.row].grade!))级"
        if subUserList[indexPath.row].grade == "B"{
            gradeLabel.textColor = UIColor.blue
        } else {
            gradeLabel.textColor = UIColor.green
        }
        
        // 2
        let nameLabel:UILabel = cell.viewWithTag(2) as! UILabel
        nameLabel.text = subUserList[indexPath.row].realname
        
        // 3
        let incomeLabel:UILabel = cell.viewWithTag(3) as! UILabel
        incomeLabel.text = "累计收益：\(Int(arc4random_uniform(5000))+1001)元"
        
        // 4
        let deadlineLabel:UILabel = cell.viewWithTag(4) as! UILabel
        
        let nowDate = Date()
        let timeZone = TimeZone.init(identifier: "UTC")
        let formatter = DateFormatter()
        formatter.timeZone = timeZone
        formatter.locale = Locale.init(identifier: "zh_CN")
        formatter.dateFormat = "yyyy/MM/dd"
        deadlineLabel.text = formatter.string(from: nowDate)
        
        return cell
    }
}
